using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using fitnesstrack.library;

namespace fitnesstrack.win
{
    public partial class MainForm : Form
    {
        public MainForm()
        {
            InitializeComponent();
            _main = this;
        }

        private static MainForm _main;

        internal static MainForm Instance
        {
            get { return _main; }
        }

        private void MainForm_Load(object sender, EventArgs e)
        {
            if (Csla.ApplicationContext.AuthenticationType == "Windows")
                AppDomain.CurrentDomain.SetPrincipalPolicy(
                  System.Security.Principal.PrincipalPolicy.WindowsPrincipal);
            else
                DoLogin();

            InitializeTracker();

        }

        private void InitializeTracker() {
            CategoryList cats = CategoryList.GetCategoryList();
            foreach(CategoryInfo cat in cats)
            {
                ToolStripButton btn = new ToolStripButton(cat.Name);
                btn.Name = cat.Id.ToString();
                btn.Click += new EventHandler(WorkoutCategoryButton_Click);
                WorkoutToolstripButton.DropDownItems.Add(btn);
            }
        }

        void WorkoutCategoryButton_Click(object sender, EventArgs e)
        {
            int id = int.Parse(((ToolStripButton) sender).Name);
            WorkoutForm workout = new WorkoutForm(id);
            workout.Show();
        }

        private void DoLogin()
        {
            FitnessPrincipal.Logout();

            if (this.LoginToolStripButton.Text == "Login")
            {
            LoginForm loginForm = new LoginForm();
            loginForm.ShowDialog(this);
            }

            System.Security.Principal.IPrincipal user =
              Csla.ApplicationContext.User;

            if (user.Identity.IsAuthenticated)
            {
                this.LoginToolStripLabel.Text = "Logged in as " +
                  user.Identity.Name;
                this.LoginToolStripButton.Text = "Logout";
            }
            else
            {
                this.LoginToolStripLabel.Text = "Not logged in";
                this.LoginToolStripButton.Text = "Login";
            }

            //// reset menus, etc.
            //ApplyAuthorizationRules();

            //// notify all documents
            //foreach (Control ctl in Panel1.Controls)
            //    if (ctl is WinPart)
            //        ((WinPart)ctl).OnCurrentPrincipalChanged(this, EventArgs.Empty);
        }

        private void LoginToolStripButton_Click(object sender, EventArgs e)
        {
            DoLogin();
        }
    }
}